<?php

/**
 * @author Jeevan Tomson
 * @copyright 2011
 */

class LabelManager {

    private $db;
    private $logger;
    
    private static $labels;
    
    private $lang;
    
    public function __construct($lang = 1) {
		global $db;
		$this->db = $db;
        $this->logger = Logger::getLogger(__CLASS__);

        if( !isset(self::$labels) ) {
            $this->loadLabel($lang);
        }
	}
    
    public function loadLabel($lang) {
        self::$labels = array();
        try {
            $sql  = "SELECT id, name, value ";
            $sql .= "FROM labels lb LEFT JOIN labellang lg ";
            $sql .= "ON ( lb.id = lg.labelid AND lg.langid = ".$lang." )";
            if($this->logger->isDebugEnabled()) {
		      $this->logger->debug("Load label sql: ".$sql);
            }
            
            $recordSet = $this->db->CacheExecute($sql); 
            
            if (!$recordSet) {
               $this->logger->Error("loadLabel: ".$sql);
            } else {
                while (!$recordSet->EOF) {
                    if( $recordSet->fields["value"] != NULL )
                        self::$labels[$recordSet->fields["name"]] = $recordSet->fields["value"];
                    else
                        self::$labels[$recordSet->fields["name"]] = $recordSet->fields["name"];
                    $recordSet->MoveNext(); 
                }
                $recordSet->Close(); # optional    
            }    
        } catch(Exception $e) {
            $this->logger->Error("Exception in loadLabel: ".$e); 
        }
    }
    
    public function getLanguageList() {
        $langs = array();
        
        try {
            $sql  = "SELECT * FROM language";
            if($this->logger->isDebugEnabled()) {
		      $this->logger->debug("Load language sql: ".$sql);
            }
            
            $recordSet = $this->db->CacheExecute($sql);
            
            if (!$recordSet) {
               $this->logger->Error("getLanguageList: ".$sql);
            } else {
                while (!$recordSet->EOF) {
                $lang = array(); 
                    $lang["id"] = $recordSet->fields["Id"];
                    $lang["name"] = $recordSet->fields["Name"];
                    $lang["code"] = $recordSet->fields["Code"];
                    $lang["dir"] = $recordSet->fields["Dir"];
                    array_push($langs,$lang);                        
                    $recordSet->MoveNext(); 
                }
                $recordSet->Close(); # optional    
            }  
        } catch (Exception $e) {
            $this->logger->Error("Exception in getLanguageList: ".$e);
        }
        
        return $langs;
    }
    
    public function getLabel($name) {
        if(isset(self::$labels[$name]))
            return self::$labels[$name];
        else
            return "Undefined";
    }
    
    public function addLabel( $name, $langs ) {
        if(!$this->isLabelExist($name))
        {
            $id = $this->insertLabel($name);
            if($id != "") {
                foreach( $langs as $lang ) {
                    $lang["value"] = trim($lang["value"]);
                    
                    if(isset($lang["value"]) && $lang["value"] != "" ) {
                        $this->addLabelLang($id, $lang["id"], $lang["value"]);
                    }
                }
            }    
        }        
    }
    
    private function addLabelLang( $labelid, $langid, $value ) {
        try{
            $record["LabelId"] = $labelid;
            $record["LangId"] = $langid;
            $record["Value"] = $value;
            
            $inserted = $this->db->AutoExecute('labellang', $record, 'INSERT');
            
            if($this->logger->isDebugEnabled()) {
    	      $this->logger->debug("addLabelLang inserted: LabelId=$labelid, LangId=$langid, Value=$value");
            }
        } catch(Exception $e){
            $this->logger->Error("Exception in addLabelLang: ".$e);
        }
    }
    
    private function insertLabel( $name ){
        try {
            $record["name"] = $name;
            $inserted = $this->db->AutoExecute('labels', $record, 'INSERT');
            $labelid = $this->db->Insert_ID();
            if($this->logger->isDebugEnabled()) {
		      $this->logger->debug("New label Added: id=".$labelid.", name=".$name);
            }
            return $labelid;    
        } catch (Exception $e) {
            $this->logger->Error("Exception in insertLabel: ".$e);   
        }
        return "";
    }
    
    public function updateLabel( $labelid, $langs ) {
        
        try{
            if($labelid != "") {
    
                foreach( $langs as $lang ) {
                    $record = array();
                    
                    if(isset($lang["value"]) && $lang["value"] != "" ) {
                        $record["Value"] = $lang["value"];
                        
                        if($this->isLabelLang($labelid, $lang["id"])) {
                            $updated = $this->db->AutoExecute('labellang', $record, 'UPDATE','LabelId = '.$labelid.' AND LangId = '.$lang["id"]);
                            if($this->logger->isDebugEnabled())
                                $this->logger->debug("Label lang updated: LabelId=$labelid, LangId=".$lang["id"].", Value=".$record["Value"]);
                        } else {
                            $record["LabelId"] = $labelid;
                            $record["LangId"] = $lang["id"];
                            $updated = $this->db->AutoExecute('labellang', $record, 'INSERT');
                            if($this->logger->isDebugEnabled())
                                $this->logger->debug("Label lang inserted: LabelId=$labelid, LangId=".$record["LangId"].", Value=".$record["Value"]);
                        }
                        
                        if($this->logger->isDebugEnabled()) {
            		      $this->logger->debug("Affected rows = ".$this->db->Affected_Rows());
                          
                        }
                    }   
                }
            }
        } catch (Exception $e) {
            $this->logger->error("Exception in updateLabel : ".$e);
        }    
    }
    
    private function isLabelExist($name) {
        $sql = "SELECT if( COUNT( * ) >0, true, false ) AS ISEXIST FROM labels WHERE name = '".$name."'";
        $data = $this->db->GetRow($sql);
        return $data["ISEXIST"];    
    }
    
    private function isLabelLang( $labelid, $langid ) {
        $sql = "SELECT if( COUNT( * ) >0, true, false ) AS ISEXIST FROM labellang WHERE LabelId = ".$labelid." AND LangId = ".$langid;
        $data = $this->db->GetRow($sql);
        return $data["ISEXIST"];
    }
    
    public function getLabelCount()
    {
        try {
            $sql  = "SELECT COUNT(*) AS LabelCount FROM labels";
            if($this->logger->isDebugEnabled()) {
		      $this->logger->debug("Get Label count sql: ".$sql);
            }            
            
            $recordSet = $this->db->Execute($sql); 
            
            if (!$recordSet) {
               $this->logger->Error("LabelCount: ".$sql);
            } else {
                $labelCount = $recordSet->fields["LabelCount"];
                $recordSet->Close(); # optional                
            }             
            return $labelCount;   
        } catch(Exception $e) {
            $this->logger->Error("Exception in getLabelCount: ".$e); 
        }        
        return "";    
    }
    
    public function getLabelsList( $page, $size, $name = "") {
        try {
    		$page = $page * $size;
    		$sql  = "SELECT * FROM labels ";		
    		if( $name!= "" )
    		  $sql  .=  "WHERE name like '%".$name."%' ";		
    		$sql .= "order by name asc ";
    		if( isset($page) && isset($size) )
    		$sql .= "LIMIT $page, $size";
    		if($this->logger->isDebugEnabled()) {
		      $this->logger->debug("getLabelsList sql: ".$sql);
            }
            
            //echo $sql; exit;
            
            $recordSet = $this->db->Execute($sql);
            $labelList = array();
            if (!$recordSet) {
               $this->logger->Error("getLabelsList: ".$sql);
            } else {
                while (!$recordSet->EOF) {
                    applyStripSlashes($recordSet->fields);  
                    array_push($labelList,$recordSet->fields);	
                    
                    $recordSet->MoveNext(); 
                }
                $recordSet->Close(); # optional    
            }    		
    		return $labelList;
            
        } catch(Exception $e) {
            $this->logger->Error("getLabelsList in getLabelsList: ".$e); 
        }        
        return "";
	}  
    
    public function getLabelDetails($labelid) {
        $labelDetails = array();
        try {
            $sql = "SELECT la.id AS LangId, lg.value, la.Name as LangName FROM labellang lg ";
            $sql .= "RIGHT JOIN Language la ON ( la.id = lg.langid AND lg.labelid =".$labelid.")";
            
            if($this->logger->isDebugEnabled()) {
		      $this->logger->debug("getLabelDetails: ".$sql);
            }
            
            $recordSet = $this->db->Execute($sql); 
            
            if (!$recordSet) {
               $this->logger->Error("getLabelDetails: ".$sql);
            } else {
                while (!$recordSet->EOF) {
                    
                    $labs = array("id" => $recordSet->fields["LangId"], "value" => $recordSet->fields["value"], "langName" => $recordSet->fields["LangName"]);                    
                    array_push($labelDetails,$labs);
                    $recordSet->MoveNext();                   
                }
                $recordSet->Close(); # optional    
            }
            
            return $labelDetails;    
        } catch(Exception $e) {
            $this->logger->Error("Exception in loadLabel: ".$e); 
        }
        
        return "";
    } 
    
    public function getLabelEngValue($labelid) 
    {
        try {
            $sql = "SELECT name FROM labels WHERE id = ".$labelid;
            if($this->logger->isDebugEnabled()) {
		      $this->logger->debug("getLabelEngValue sql: ".$sql);
            }
            
            $recordSet = $this->db->Execute($sql); 
            
            if (!$recordSet) {
               $this->logger->Error("LabelEngValue: ".$sql);
            } else {
                $labelEngValue = $recordSet->fields["name"];
                $recordSet->Close(); # optional                
            }             
            return $labelEngValue; 
            
        } catch(Exception $e) {
            $this->logger->Error("Exception in loadLabel: ".$e); 
        }
        return "";
    }
}

?>